package com.itheima.dubbo.mysql.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.commons.model.domain.Settings;
import com.itheima.dubbo.interfaces.SettingsApi;
import com.itheima.dubbo.mysql.mapper.SettingsMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@Service
public class SettingsApiImpl implements SettingsApi {

    @Autowired
    private SettingsMapper settingsMapper;

    /**
     * 根据用户id查询配置
     *
     * @param userId
     * @return
     */
    public Settings querySettings(Long userId) {
        return settingsMapper.selectOne(Wrappers.lambdaQuery(Settings.class)
                .eq(Settings::getUserId, userId));
    }


    /**
     * 更新通知
     *
     * @param userId
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    @Override
    public void updateNotification(Long userId, Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        //查询用户的设置
        Settings settings = querySettings(userId);
        if (ObjectUtil.isEmpty(settings)) {
            settings = new Settings();
            settings.setUserId(userId);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setCreated(new Date());
            settings.setUpdated(settings.getCreated());
            settingsMapper.insert(settings);
        } else {
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setUpdated(new Date());
            settingsMapper.updateById(settings);
        }
    }
}
